#!/usr/bin/python
# -*- coding: utf-8 -*-

from lib.services import GoogleTTS
from lib.util import *
        
class BaseTTSService(object):
    def __init__(self,text):
        self.tts=GoogleTTS()
        self.text=text
        self.data=None
        
class EnTTSService(BaseTTSService):
    """英文发音，使用 Google TTS"""
    def __init__(self,text):
        super(EnTTSService,self).__init__(text)        
        
    def load(self):
        self.data=self.tts.request('en',self.text)
        return self.data
    
class ZhTTSService(BaseTTSService):
    """中文发音，使用 Google TTS"""
    def __init__(self,text):
        super(ZhTTSService,self).__init__(text)
        
    def load(self):
        self.data=self.tts.request('zh_CN',self.text.decode("gbk").encode("utf-8"))
        return self.data
    
    
class TTSObj(object):
    def __init__(self):
        self.data=None
    
    def load(self,service):
        try:
            self.data=service.load()
        except urllib2.HTTPError,e:
            print e
            
    def loadAndSave(self,serv,f):
        self.load(serv)
        if self.data:
            f.write(self.data)

            
def start():
    f=open("words.txt","r")
    lines=f.readlines()
    
    for line in lines:
        pair=line.split()
        en,zh=pair[0],pair[1]
        print "%s\t\t%s" % (en,zh)

        f=File("data\\tts\\%s_en.mp3" % en)
        if f.exists():
            continue
        obj=TTSObj()
        obj.loadAndSave(EnTTSService(en),f)
        Media.speak(obj.data)
        
        
        f=File("data\\tts\\%s_zh.mp3" % en)
        if f.exists():
            continue
        obj=TTSObj()
        obj.loadAndSave(ZhTTSService(zh),f)
        Media.speak(obj.data)
        
        
if __name__=='__main__':
    start()


        